//
//  LoginViewController.swift
//  SwiftProject
//
//  Created by qindong on 2021/3/16.
//

import UIKit
import AttributedString

class LoginViewController: BaseViewController {
    //电话号码输入
    let phoneNumberTextField = QMUITextField()
    //验证码输入
    let codeTextField = QMUITextField()
    //获取验证码按钮
    let getCodeButton = QMUIButton()
    // 同意协议按钮
    let agreeBtn = QMUIButton()
    //登录按钮
    let loginButton = QMUIButton()

    //加载登录ViewModel
    lazy var loginViewModel : LoginViewModel = {
        LoginViewModel(phoneNumber: phoneNumberTextField.rx.text.orEmpty.asDriver(), code: codeTextField.rx.text.orEmpty.asDriver())
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        navigationBarType = .clear
    }
    
    override func initSubviews() {
        super.initSubviews()
        view.backgroundColor = .white
        
        let imageV = UIImageView(imageString: "icon_login_background")
        view.addSubview(imageV)
        
        imageV.snp.makeConstraints { make in
            make.right.top.equalToSuperview()
        }
        
        let titleLb = QMUILabel(font: .bSFont(28), textColor: .color51)
        titleLb.text = "你好，\n欢迎来到宝银钱包"
        titleLb.numberOfLines = 0
        view.addSubview(titleLb)
        
        titleLb.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.top.equalTo(NavigationContentTop + 40)
        }
        
        phoneNumberTextField.clearButtonMode = .whileEditing
        phoneNumberTextField.placeholder = "请输入手机号"
        phoneNumberTextField.placeholderColor = .color206
        phoneNumberTextField.font = .rSFont(16)
        phoneNumberTextField.keyboardType = .phonePad
        phoneNumberTextField.qmui_borderWidth = 0.5
        phoneNumberTextField.qmui_borderColor = .qmui_color(withHexString: "DCDCDC")
        phoneNumberTextField.qmui_borderPosition = .bottom
        phoneNumberTextField.textContentType = .telephoneNumber
        view.addSubview(phoneNumberTextField)
        
        phoneNumberTextField.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.height.equalTo(50)
            make.top.equalTo(titleLb.snp.bottom).offset(30)
        }
        
        codeTextField.clearButtonMode = .whileEditing
        codeTextField.placeholderColor = .color206
        codeTextField.font = .rSFont(16)
        codeTextField.rightViewMode = .always
        codeTextField.keyboardType = .phonePad
        codeTextField.qmui_borderWidth = 0.5
        codeTextField.qmui_borderColor = .qmui_color(withHexString: "DCDCDC")
        codeTextField.qmui_borderPosition = .bottom
        codeTextField.textContentType = .oneTimeCode
        codeTextField.keyboardType = .numberPad
        codeTextField.placeholder = "请输入验证码"
        view.addSubview(codeTextField)
        
        codeTextField.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(phoneNumberTextField)
            make.top.equalTo(phoneNumberTextField.snp.bottom).offset(28)
        }
        // 创建一个中间view 防止textfield.rightview设置button时压缩
        let rightV = UIView()
        let rightBtn = QMUIButton()
        rightBtn.contentMode = .scaleAspectFill
        rightBtn.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
        rightBtn.frame = CGRect(x: 0, y: 0, width: 84, height: 28)
        // button 点击绑定
        rightBtn.rx.tap.subscribe(onNext:{ [weak self] _ in
            guard let self = self else {
                return
            }
            if self.phoneNumberTextField.text?.count != 11 {
                QMUITips.showError(self.phoneNumberTextField.placeholder)
                return
            }
            let aesPhone = WMEncryptTool.manager.aesEncrypt(self.phoneNumberTextField.text!)
            NetworkManager.manager.request(targetType: .authCaptcha(phoneAes: aesPhone), responseModelType: NetworkDefualtModel.self) { responseModel in
                if responseModel.code != .successCode {
                    QMUITips.showError(responseModel.msg)
                    return
                }
                rightBtn.countdownButtonWith(timeout: 60) { button, time in
                    button.setTitle("已发送(\(time))", for: .normal)
                    rightBtn.setBackgroundImage(.qmui_image(with: .color206), for: .normal)
                    self.codeTextField.becomeFirstResponder()
                } completeBlock: { button in
                    button.setTitle("获取验证码", for: .normal)
                    rightBtn.setBackgroundImage(.qmui_image(withGradientColors: [.qmui_color(withHexString: "3C58A2")!, .qmui_color(withHexString: "2C304E")!], type: .horizontal, locations: nil, size: rightBtn.frame.size, cornerRadiusArray: nil), for: .normal)
                }
            }
        }).disposed(by: rx.disposeBag)
        rightV.addSubview(rightBtn)
        codeTextField.rightView = rightV

        rightV.frame = CGRect(x: 0, y: 0, width: 84, height: 28)
        rightBtn.setTitle("获取验证码", for: .normal)
        rightBtn.setBackgroundImage(.qmui_image(withGradientColors: [.qmui_color(withHexString: "3C58A2")!, .qmui_color(withHexString: "2C304E")!], type: .horizontal, locations: nil, size: rightBtn.frame.size, cornerRadiusArray: nil), for: .normal)
        rightBtn.setTitleColor(.white, for: .normal)
        rightBtn.titleLabel?.font = .rSFont(13)
        rightBtn.layer.cornerRadius = 14
        rightBtn.clipsToBounds = true
        
        agreeBtn.setImage(UIImage(named: "icon_agreement_off"), for: .normal)
        agreeBtn.setImage(UIImage(named: "icon_agreement_on"), for: .selected)
        view.addSubview(agreeBtn)
        
        agreeBtn.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.top.equalTo(codeTextField.snp.bottom).offset(24)
            make.size.equalTo(15)
        }
        agreeBtn.rx.tap.subscribe ({ [weak self] _ in
            if let self = self {
                self.agreeBtn.isSelected.toggle()
                self.loginViewModel.buttonIsSelected.accept(self.agreeBtn.isSelected)
            }
        }).disposed(by: rx.disposeBag)
        
        let agreementLb = QMUILabel()
        agreementLb.isUserInteractionEnabled = true
        agreementLb.font = .rSFont(12)
        agreementLb.textColor = .color153
        view.addSubview(agreementLb)
        
        agreementLb.snp.makeConstraints { (make) in
            make.centerY.equalTo(agreeBtn)
            make.left.equalTo(agreeBtn.snp.right).offset(4)
            make.right.equalTo(-30)
        }

        var str : ASAttributedString = """
        已阅读并同意\("《用户服务协议》", .action { [unowned self] in
                    let vc = BaseWebViewController(.local("agreement01", "html"))
                    self.navigationController?.qmui_pushViewController(vc, animated: true)
        })与\("《用户隐私政策》", .action {  [unowned self] in
                    let vc = BaseWebViewController(.local("agreement02", "html"))
                    self.navigationController?.qmui_pushViewController(vc, animated: true)
        })
        """
        str.add(attributes: [.foreground(.colorMain)], checkings: [.action])
        agreementLb.attributed.text = str
        
        loginButton.setBackgroundImage(.qmui_image(withGradientColors: [.qmui_color(withHexString: "3C58A2")!, .qmui_color(withHexString: "2C304E")!], type: .horizontal, locations: nil, size: rightBtn.frame.size, cornerRadiusArray: nil), for: .normal)
        loginButton.isEnabled = false
        loginButton.setTitle("登录", for: .normal)
        loginButton.titleLabel?.font = .mSFont(20)
        loginButton.setTitleColor(.white, for: .normal)
        loginButton.layer.cornerRadius = 26
        loginButton.clipsToBounds = true
        view.addSubview(loginButton)
        
        loginButton.snp.makeConstraints { (make) in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.height.equalTo(52)
            make.top.equalTo(codeTextField.snp.bottom).offset(58)
        }
        
        loginButton.rx.tap.subscribe(onNext: { [unowned self] _ in
            if self.codeTextField.text!.isEmpty {
                QMUITips.showError(self.codeTextField.placeholder)
                return
            }
            let aesPhone = WMEncryptTool.manager.aesEncrypt(self.phoneNumberTextField.text!)
            NetworkManager.manager.request(targetType: .authAppLogin(phoneAes: aesPhone, captcha: self.codeTextField.text!), responseModelType: NetworkBaseModel<BaseUserModel>.self) { responseModel in
                if responseModel.code != .successCode {
                    QMUITips.showError(responseModel.msg)
                    return
                }
                QMUITips.showSucceed("登录成功")
                responseModel.data!.phone = self.phoneNumberTextField.text!
                responseModel.data?.archiver()
                if self.isMovingToParent {
                    self.dismiss(animated: true)
                } else {
                    AppDelegate.appDelegate.window?.rootViewController = TabbarController()
                }
            }
        }).disposed(by: rx.disposeBag)
        
        loginViewModel.validateLoginButton.drive(loginButton.rx.buttonIsEnable).disposed(by: rx.disposeBag)
    }
    
    override func baseBackBtnAction(btn: UIButton) {
        dismiss(animated: true, completion: nil)
    }
    
    override func setupNavigationItems() {
        super.setupNavigationItems()
        navigationItem.rightBarButtonItem = closeBtn()
        navigationItem.rightBarButtonItem?.tintColor = .black
    }
    
    override func customNavigationBarTransitionKey() -> String? {
        "login"
    }
}

